#include "../main.h"
#define MAXBUF 102400

void keep_connect(int sockfd)
{
    pthread_t pt_ping;
    pthread_create(&pt_ping, NULL, (void *)send_ping_thread, &sockfd);
}

void *nas_client(void *arg)
{
    int sockfd, len;
    struct sockaddr_in dest;
    char buffer[MAXBUF + 1];
    fd_set rfds;
    struct timeval tv;
    int retval, maxfd = -1;

    /* 创建一个 socket 用于 tcp 通信 */
    if ((sockfd = socket(AF_INET, SOCK_STREAM, 0)) < 0)
    {
        perror("Socket");
        exit(errno);
    }

    /* 初始化服务器端（对方）的地址和端口信息 */
    bzero(&dest, sizeof(dest));
    dest.sin_family = AF_INET;
    dest.sin_port = htons(9002);
    printf("server:%s\n", Server);
    if (inet_aton(Server, (struct in_addr *)&dest.sin_addr.s_addr) == 0)
    {
        OUT_DEBUG(DEBUG, "address error");
        exit(errno);
    }
    /* 连接服务器 */
    if (connect(sockfd, (struct sockaddr *)&dest, sizeof(dest)) != 0)
    {
        OUT_DEBUG(DEBUG, "Connect to server error");
        exit(errno);
    }
    OUT_DEBUG(DEBUG, "Connect to server successful!");
    keep_connect(sockfd);
    while (1)
    {
        FD_ZERO(&rfds);
        FD_SET(0, &rfds);
        maxfd = 0;
        FD_SET(sockfd, &rfds);
        if (sockfd > maxfd)
        {
            maxfd = sockfd;
        }
        tv.tv_sec = 1;
        tv.tv_usec = 0;
        retval = select(maxfd + 1, &rfds, NULL, NULL, &tv);
        if (retval == -1)
        {
            OUT_DEBUG(DEBUG, "将退出，select出错！ %s", strerror(errno));
            break;
        }
        else if (retval == 0)
        {
            /* OUT_DEBUG(DEBUG,"没有任何消息到来，用户也没有按键，继续等待……\n"); */
            continue;
        }
        else
        {
            if (FD_ISSET(sockfd, &rfds))
            {
                /* 连接的socket上有消息到来则接收对方发过来的消息并显示 */
                bzero(buffer, MAXBUF + 1);

                /* 接收对方发过来的消息，最多接收 MAXBUF 个字节 */
                len = recv(sockfd, buffer, MAXBUF, 0);
                if (len > 0)
                {
                    nas_recv_data(sockfd, buffer, len);
                }
                else
                {
                    if (len < 0)
                    {
                        OUT_DEBUG(DEBUG, "消息接收失败！错误代码是%d，错误信息是'%s'\n", errno, strerror(errno));
                    }
                    else
                    {
                        OUT_DEBUG(DEBUG, "对方退出了，聊天终止！\n");
                    }
                    break;
                }
            }
        }
    }
    /* 关闭连接 */
    close(sockfd);
    return NULL;
}

//接收消息处理
void nas_recv_data(int sockfd, char *data, int length)
{
    char bufcopy[length];
    memset(bufcopy, 0, length);
    memcpy(bufcopy, data, length);
    appendData(sockfd, bufcopy, length);
}